﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Depart;
using User.Api.HttpClients;
using System.Configuration;

namespace User.Api.Controllers
{
 
    public class DepartController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DepartController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有科室信息
        /// </summary>
        /// <param name="orderType">0-预约 2-当天</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll(string type = "detail")
        {
            if (type == "detail")
            {
                //var branchNo = DepartExtensions.ToBranchNo(branchName);
                var depart = _ctx.Depart.Where(x => x.RecStatus != 2);
                //if (!string.IsNullOrEmpty(branchNo))
                //{
                //    departs = departs.Where(x => x.BranchNo == branchNo);
                //}
                var departList = depart.OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

                return new GetAllResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = departList.Select(x => new GetAllResponse.Depart
                    {
                        BranchName = DepartExtensions.ToBranchName(x.BranchNo),
                        DepartId = x.DeptId,
                        DepartName = x.DeptName
                    }).ToList()
                };
            }
            else
            {
                //var branchNo = DepartExtensions.ToBranchNo(branchName);
                var departs = _ctx.Depart.Where(x => x.RecStatus == 3);
                //if (!string.IsNullOrEmpty(branchNo))
                //{
                //    departs = departs.Where(x => x.BranchNo == branchNo);
                //}
                var departsList = departs.OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

                return new GetAllResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = departsList.Select(x => new GetAllResponse.Depart
                    {
                        BranchName = DepartExtensions.ToBranchName(x.BranchNo),
                        DepartId = x.DeptId,
                        DepartName = x.DeptName
                    }).ToList()
                };
            }
        }

        /// <summary>
        /// 根据科室院内编号获取科室信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetByDeptId")]
        public GetByDeptIdResponse GetByDeptId(string deptId)
        {
            var depart = _ctx.Depart.FirstOrDefault(x => x.DeptId == deptId);
            if (depart == null)
            {
                return new GetByDeptIdResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到科室",
                };
            }

            var doctors = _ctx.Doctor.Where(x => x.RecStatus == 1 && x.DeptId == deptId)
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return new GetByDeptIdResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Name = depart.DeptName,
                Position = depart.Loc,
                Desc = string.IsNullOrEmpty(depart.Desc) ? "暂无介绍" : depart.Desc,
                Drs = doctors.Select(x => new GetByDeptIdResponse.Dr
                {
                    DoctorId = x.DoctorId,
                    DeptId = x.DeptId,
                    Name = x.DoctorName,
                    Sex = DoctorExtensions.ToZhSex(x.Gender),
                    Title = x.Title
                }).ToList()
            };
        }

        /// <summary>
        /// 搜索科室或医生
        /// </summary>
        /// <param name="keyword">科室或医生的名称，包含关系</param>
        /// <param name="orderType">0：预约 2：当天</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SearchDepartOrDr")]
        public SearchDepartOrDrResponse SearchDepartOrDr(string keyword, string type = "detail")
        {
            if (type == "detail")
            {
                var depart = _ctx.Depart.Where(x => x.RecStatus == 1 && x.DeptName.Contains(keyword))
              .OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

                var doctor = _ctx.Doctor.Where(x => x.RecStatus == 1 && x.DoctorName.Contains(keyword))
                    .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

                return new SearchDepartOrDrResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = depart.Select(x => new SearchDepartOrDrResponse.Depart
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DeptName
                    }).ToList(),
                    Drs = doctor.Select(x => new SearchDepartOrDrResponse.Dr
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DepartName,
                        DrId = x.DoctorId,
                        DrName = x.DoctorName,
                        Sex = DoctorExtensions.ToZhSex(x.Gender),
                        Title = x.Title,
                    }).ToList()
                };
            }
            else
            {
                var departs = _ctx.Depart.Where(x => x.RecStatus == 3 && x.DeptName.Contains(keyword))
               .OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

                var doctors = _ctx.Doctor.Where(x => x.RecStatus == 1 && x.DoctorName.Contains(keyword))
                    .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

                return new SearchDepartOrDrResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = departs.Select(x => new SearchDepartOrDrResponse.Depart
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DeptName
                    }).ToList(),
                    Drs = doctors.Select(x => new SearchDepartOrDrResponse.Dr
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DepartName,
                        DrId = x.DoctorId,
                        DrName = x.DoctorName,
                        Sex = DoctorExtensions.ToZhSex(x.Gender),
                        Title = x.Title,
                    }).ToList()
                };
            }
                    
        }

        /// <summary>
        /// 获取排班信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <param name="doctorId">医生院内编号，为空表示查询科室内所有医生</param>
        /// <param name="orderType">0：预约 2：当天</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetTimeSlices")]
        public GetTimeSlicesResponse GetTimeSlices(string deptId, string doctorId)
        {
            var res = new GetTimeSlicesResponse
            {
                DefaultSelectedDay = "无剩余号源",
                Today = DateTime.Now.ToString("yyyy-MM-dd"),
                RegDays = new List<GetTimeSlicesResponse.ScheduleDay>()
            };

            //if (orderType == "2")
            //{
            //    //当天挂号限制
            //    #region (8点前不能挂号,12:00-14:30不能挂号)
            //    if (System.DateTime.Now.Hour < 8)
            //    {
            //        res.ResultCode = "1";
            //        res.ResultMsg = "很抱歉，现在还不是挂号时间，请您于8点后再挂号！";
            //        return res;
            //    }
            //    if (System.DateTime.Now.Hour >= 12 && (String.Compare(DateTime.Now.ToString("HH:mm"), "14:30", StringComparison.Ordinal) < 0))
            //    {
            //        res.ResultCode = "1";
            //        res.ResultMsg = "很抱歉，现在还不是挂号时间，请您于14点30分后再挂号！";
            //        return res;
            //    }

            //    #endregion
            //}

            for (int i = 0; i < 8; i++)
            {
                res.RegDays.Add(new GetTimeSlicesResponse.ScheduleDay
                {
                    Date = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    IsFull = true,
                    TimeSlices = new List<GetTimeSlicesResponse.TimeSlice>()
                });
            }

            // 获取排班
            var request = new Request4GetScheduleInfo
            {
                DeptId = deptId,
                DoctorId = doctorId,
                BeginDate = DateTime.Now.ToString("yyyy-MM-dd"),
                EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd")
            };

            Response4GetScheduleInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetScheduleInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetScheduleInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "1";
                res.ResultMsg = "获取排班超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "2";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            var scheduleInfos = response.ScheduleList;

            foreach (var scheduleInfo in scheduleInfos)
            {
                //已停诊和已经结束的排班不显示
                if (scheduleInfo.IsHalt == "0" &&
                    (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) > 0
                     ||
                     (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) == 0
                      && String.CompareOrdinal(scheduleInfo.EndTime, DateTime.Now.ToString("HH:mm")) > 0)))
                {
                    //挂号提前30分钟放号
                    if (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) == 0
                        &&
                        (String.CompareOrdinal(scheduleInfo.StartTime, DateTime.Now.AddMinutes(30).ToString("HH:mm")) >
                         0 //未到时间                                                                        
                         || String.CompareOrdinal(scheduleInfo.EndTime, DateTime.Now.ToString("HH:mm")) < 0 //已过时间 
                            )
                        )
                    {
                        continue;
                    }

                    var scheduleDay = res.RegDays.First(x => x.Date == scheduleInfo.RegDate);
                    if (scheduleInfo.TotalCount == "不限号" || scheduleInfo.LeaveCount.ToInt32OrDefault() > 0)
                    {
                        scheduleDay.IsFull = false;
                        if (res.DefaultSelectedDay == "无剩余号源")
                        {
                            res.DefaultSelectedDay = scheduleInfo.RegDate;
                        }
                    }

                    scheduleDay.TimeSlices.Add(new GetTimeSlicesResponse.TimeSlice
                    {
                        DeptId = scheduleInfo.DeptId,
                        DeptName = scheduleInfo.DeptName,
                        DoctorId = scheduleInfo.DoctorId,
                        DoctorName = scheduleInfo.DoctorName,
                        Title = scheduleInfo.Title,
                        RegType = scheduleInfo.RegType,
                        SliceName = scheduleInfo.TimeSlice,
                        SliceStartTime = scheduleInfo.StartTime,
                        SliceEndTime = scheduleInfo.EndTime,
                        LeaveCount =
                            scheduleInfo.LeaveCount.ToInt32OrDefault() < 0
                                ? 0
                                : scheduleInfo.LeaveCount.ToInt32OrDefault(),
                        TotalCount = scheduleInfo.TotalCount.ToInt32OrDefault(),
                        HasTimePoint = scheduleInfo.IsTimeFlag == "1",
                        //RegFee = scheduleInfo.Fee.ToDecimalOrDefault(),
                        //TreatFee = scheduleInfo.TreatFee.ToDecimalOrDefault(),
                        //OtherFee = scheduleInfo.OtherFee.ToDecimalOrDefault(),
                        //TotalFee =
                        //    scheduleInfo.Fee.ToDecimalOrDefault() + scheduleInfo.TreatFee.ToDecimalOrDefault() +
                        //    scheduleInfo.OtherFee.ToDecimalOrDefault()
                    });

                }
            }

            res.ResultCode = "0";
            res.ResultMsg = "";
            return res;
        }

        public class RegScheduleInfoComparer : IComparer<Response4GetScheduleInfoSubScheduleInfo>
        {
            public int Compare(Response4GetScheduleInfoSubScheduleInfo x, Response4GetScheduleInfoSubScheduleInfo y)
            {
                var rtn = String.Compare(GetNewTime(x.StartTime), GetNewTime(y.StartTime), StringComparison.Ordinal);
                if (rtn == 0)
                {
                    rtn = String.Compare(x.DoctorName, y.DoctorName, StringComparison.Ordinal);
                } 
                return rtn;
            }
        }

        private static string GetNewTime(string strTime)
        {
            if (string.IsNullOrEmpty(strTime))
                return "23:59";
            if (strTime.Trim().Length < 5)
                return "0" + strTime;
            return strTime;
        }
    }    
}
